import { IMiddleware } from "koa-router";
import { Model } from "mongoose";
import { JSONSchemaType } from "ajv";

import { validateParams } from "../middleware/validate";
import { ajv } from "../util/ajv";
import { makeResponse, HttpStatusCode } from "../util/response";

// 检测分页参数有效性
export function pageValidator() {
  const returnMiddleware: IMiddleware = async (ctx, next) => {
    const current = ctx.query.current as any as number;
    const limit = ctx.query.limit as any as number;

    const { total } = ctx.state;
    const maxPage = Math.ceil(total / limit);
    if (current > maxPage && maxPage > 0)
      makeResponse(ctx, HttpStatusCode.BadRequest, "当前页码超出总页数");
    else await next();
  };
  return returnMiddleware;
}

// 检测 ObjectId 有效性且是否存在
interface ObjectId {
  id: string;
}

const objectIdSchema: JSONSchemaType<ObjectId> = {
  type: "object",
  properties: {
    id: { type: "string", isValidObjectId: true }
  },
  required: ["id"]
};
ajv.addSchema(objectIdSchema, "objectId");

export function objectIdValidator(model: Model<any, any, any>): IMiddleware[] {
  const returnMiddleware = [];

  const isExistMiddleware: IMiddleware = async (ctx, next) => {
    const { id } = ctx.params;
    const result = await model.findOne({ _id: id }).exec();
    if (!result) {
      makeResponse(ctx, HttpStatusCode.NotFound, "Not Found");
    } else {
      // 将查找到的放到 state 中后续使用
      ctx.state.result = result;
      await next();
    }
  };

  returnMiddleware.push(validateParams("objectId"));
  returnMiddleware.push(isExistMiddleware);

  return returnMiddleware;
}
